/**Searcher.java
 *
 * Description:
 * TODO
 *
 * Anping Zhou <anping.zhou@gmail.com>
 * Created: Jul 11, 2007
 */
package jp.ac.utokyo.pinyomi;

import java.util.ArrayList;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.BooleanClause.Occur;

/**
 * @author anping
 *
 */
public class Searcher {
	
	public static ArrayList<ResultRecord> search(String field, String q, String indexDir)  throws Exception{
		String[] fields = {field};
		String[] qs = {q};
		
		return search(fields, qs, indexDir);
	}
	
	@Deprecated
	public static ArrayList<ResultRecord> searchorg(String field, String q, String indexDir)  throws Exception{
		IndexSearcher is = new IndexSearcher(indexDir);
		Analyzer analyzer = new WhitespaceAnalyzer();
        QueryParser parser = new QueryParser(field, analyzer);
		System.out.print(q);
		Query query = parser.parse(q);
		
		Hits hits = is.search(query);

		ArrayList<ResultRecord> retv = new ArrayList<ResultRecord>();	
		for (int i = 0; i < 10 && i < hits.length(); i++) {	//output top 10
			Document doc = hits.doc(i);
			float score = hits.score(i);
			
			ResultRecord r = new ResultRecord();
			r.setTranslation(doc.get("word"));
			r.setMeaning(doc.get("dictMeaning"));
			r.setReading(doc.get("dictReading"));
			r.setLuceneScore(score);
//			System.out.println(doc.get("word"));
			retv.add(r);
		}
		
		return retv;
	}
	
	public static ArrayList<ResultRecord> search(String[] fields, String[] qs, String indexDir)  throws Exception{
		IndexSearcher is = new IndexSearcher(indexDir);
		Analyzer analyzer = new WhitespaceAnalyzer();
		
		// Check the length of fields and queries
		if(fields.length!=qs.length){
			System.err.println("Fields and querys do not match");
			return null;
		}
		
		BooleanQuery bQuery = new BooleanQuery();
		for(int i=0; i<fields.length; i++){
	        QueryParser parser = new QueryParser(fields[i], analyzer);
			Query query = parser.parse(qs[i]);
			bQuery.add(query, Occur.MUST);
		}
		
		Hits hits = is.search(bQuery);

		ArrayList<ResultRecord> retv = new ArrayList<ResultRecord>();	
		for (int i = 0; i < hits.length(); i++) {	//output top 10
			Document doc = hits.doc(i);
			float score = hits.score(i);
			
			ResultRecord r = new ResultRecord();
			r.setTranslation(doc.get("word"));
			r.setMeaning(doc.get("dictMeaning"));
			r.setReading(doc.get("dictReading"));
			r.setLuceneScore(score);
//			System.out.println(doc.get("word"));
			retv.add(r);
		}
		
		return retv;
	}
	
}
